import java.util.Deque;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-02-04
 * Time: 21:46
 */

public class MyTree {
    static class TreeNode {
        public char val;//数据域
        public TreeNode left;//左孩子地址
        public TreeNode right;//右孩子地址

        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode root;

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        this.root = A;
        return root;
    }

    //前序遍历 根 左子树 右子树
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        TreeNode cur = root;
        Deque<TreeNode> stack = new LinkedList<>();
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode tmp = stack.pop();
            cur = tmp.right;
        }
    }

    public void inorderTraversal(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<>();
        if(root == null) {
            return;
        }
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tmp = stack.pop();
            System.out.print(tmp.val+" ");
            cur = tmp.right;
        }
    }

    public void postorderTraversal(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<>();
        if(root == null) {
            return;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tmp = stack.peek();
            if(tmp.right == null || tmp.right == prev) {
                System.out.print(tmp.val+" ");
                stack.pop();
                prev = tmp;
            }else {
                cur = tmp.right;
            }
        }
        System.out.println();
    }


}